package cn.wolfcode.plus.web.controller;

import cn.wolfcode.plus.domain.Announcement;
import cn.wolfcode.plus.enums.AnnouncementEnum;
import cn.wolfcode.plus.qo.PageResult;
import cn.wolfcode.plus.qo.QueryObject;
import cn.wolfcode.plus.service.IAnnouncementService;
import cn.wolfcode.plus.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * Author wyy
 * Date 2021/2/17 23:37
 **/
@Controller
@RequestMapping("/announcement")
public class AnnouncementController {

    @Autowired
    private IAnnouncementService announcementService;

    @RequestMapping("/list")
    public String list(Model model, QueryObject qo){
        PageResult<Announcement> result = announcementService.query(qo);
        model.addAttribute("result", result);

        //所有公告级别
        AnnouncementEnum[] values = AnnouncementEnum.values();
        model.addAttribute("values",values);
        return "announcement/list";
    }

    @RequestMapping("/index")
    public String index(Model model,Long id){
        //设置为已读,向中间表中加入该员工已读公告
        Announcement announcement = announcementService.getById(id);
        if(!announcement.getIfread()){
            announcementService.addHasRead(UserContext.getCurrentUser().getId(),announcement.getId());
            //删除session已读公告
            List<Announcement> announcements = (List<Announcement>)UserContext.getSession().getAttribute("NOREAD_IN_SESSION");
            for (int i =0; i<announcements.size(); i++) {
                if(announcements.get(i).getId()==announcement.getId()){
                    announcements.remove(i);
                    UserContext.getSession().setAttribute("NOREAD_IN_SESSION",announcements);
                }
            }
            UserContext.getSession().setAttribute("NOREAD_IN_SESSION",announcements);
        }
        model.addAttribute("announcement",announcement);
        return "/announcement/index";
    }
}
